package org.thinkinbunny.financial.activity;

import java.util.Calendar;
import java.util.List;

import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.broadcast.BudgetReciver;
import org.thinkinbunny.financial.service.BudgetService;
import org.thinkinbunny.financial.util.Constant;
import org.thinkinbunny.financial.util.ServiceTimeUtil;
import org.thinkinbunny.financial.util.ShowTools;
import org.thinkinbunny.financial.view.AutoAdjustTextView;

import android.app.ActivityManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TimePicker;

public class BudgetActivity extends MyActivity implements OnClickListener,
		OnCheckedChangeListener {
	AutoAdjustTextView spending_this_week, spending_this_month;
	RelativeLayout saveBTNButton, returnBTn;
	EditText weekBudget_et, monthBudget_et, messageInput;
	SharedPreferences pref;;
	Button DateInput, TimeInput, budgetRingButton;
	ActivityManager mActivityManager;// =
										// (ActivityManager)getSystemService(ACTIVITY_SERVICE);
	CheckBox RingCheckBox;
	List<ActivityManager.RunningServiceInfo> mServiceList;// =
															// mActivityManager.getRunningServices(30);
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		setContentView(R.layout.activity_budget);
		init_UI();
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

		mServiceList = mActivityManager.getRunningServices(30);

		init_Data();
		DeleteNotification();
		if (readBudgetRing() == null) {
			budgetRingButton.setText(getString(R.string.DoRing));
		} else {
			budgetRingButton.setText(getString(R.string.cancel)+getString(R.string.DoRing));
			messageInput.setText(readBudgetRing());
		}
		super.onResume();
	}

	void init_UI() {
		spending_this_week = (AutoAdjustTextView) findViewById(R.id.spending_this_week);
		spending_this_month = (AutoAdjustTextView) findViewById(R.id.spending_this_month);

		saveBTNButton = (RelativeLayout) findViewById(R.id.SaveBtn);
		returnBTn = (RelativeLayout) findViewById(R.id.CancelBTN);
		budgetRingButton = (Button) findViewById(R.id.budgetRing_BTn);
		messageInput = (EditText) findViewById(R.id.messageInput);
		budgetRingButton.setOnClickListener(this);
		returnBTn.setOnClickListener(this);
		saveBTNButton.setOnClickListener(this);
		weekBudget_et = (EditText) findViewById(R.id.weekBudget_et);
		monthBudget_et = (EditText) findViewById(R.id.monthBudget_et);
		DateInput = (Button) findViewById(R.id.DateInput);
		TimeInput = (Button) findViewById(R.id.TimeInput);
		RingCheckBox = (CheckBox) findViewById(R.id.RingCheckBox);
		DateInput.setOnClickListener(this);
		TimeInput.setOnClickListener(this);
		RingCheckBox.setOnCheckedChangeListener(this);
		// RingCheckBox.setOnClickListener(this);
	}

	void init_Data() {
		pref = getSharedPreferences(Constant.BUDGET_SHARE, Context.MODE_PRIVATE);
		weekBudget_et.setText(pref.getInt("weekBudget", 0) + "");
		monthBudget_et.setText(pref.getInt("monthBudget", 0) + "");
		spending_this_week.setText(pref.getFloat("weekbill", 0.0f) + "￥");
		spending_this_month.setText(pref.getFloat("monthbill", 0.0f) + "￥");
		if (pref.getInt("weekBudget", -1)<(int)pref.getFloat("weekbill", 0.0f)||pref.getInt("weekBudget", -1)<(int)pref.getFloat("monthbill", 0.0f)) {
			ShowTools.toastInThread(getString(R.string.budget_more_error));
			
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {

		case R.id.DateInput:
			onCreateDialog(DATE_DIALOG).show();

			break;
		case R.id.TimeInput:

			onCreateDialog(TIME_DIALOG).show();
			break;
		case R.id.SaveBtn:
			// DbHelper.updateBudget(BudgetActivity.this, 100, 100);
			saveBudget();
			ShowTools.toast(getString(R.string.saveBudgetDone));
			break;

		case R.id.CancelBTN:
			// DbHelper.updateBudget(BudgetActivity.this, 100, 100);
			finish();
			break;
		case R.id.RingCheckBox:

			break;

		case R.id.budgetRing_BTn:
			Intent intent = new Intent();
			intent.setAction(BudgetService.ACTION);
			mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);

			mServiceList = mActivityManager.getRunningServices(100);
			if (BudgetServiceIsStart(mServiceList, BudgetService.ACTION)) {
				stopService(intent);
				budgetRingButton.setText(getString(R.string.DoRing));
				// Vibrator vibratorm = (Vibrator) getApplication()
				// .getSystemService(Service.VIBRATOR_SERVICE);
				// vibratorm.cancel();
				saveBudgetRing("", "", "");
				DeleteNotification();
			} else {
				Bundle messageBundle = new Bundle();
				if (TextUtils.isEmpty(messageInput.getText().toString().trim())
						|| TextUtils.isEmpty(DateInput.getText().toString()
								.trim())
						|| TextUtils.isEmpty(TimeInput.getText().toString()
								.trim())) {
					ShowTools.toastInThread(getString(R.string.inputMessage));
					return;
				} else if (new ServiceTimeUtil().getBudgetTimeRing(null,
						DateInput.getText().toString() + " "
								+ TimeInput.getText().toString() + ":00", null) > 0) {
					saveBudgetRing(messageInput.getText().toString().trim(),
							DateInput.getText().toString(), TimeInput.getText()
									.toString());
					messageBundle.putString("message", messageInput.getText()
							.toString().trim());
					messageBundle.putString("date", DateInput.getText()
							.toString());
					messageBundle.putString("time", TimeInput.getText()
							.toString());
					messageBundle.putBoolean("Ring", RingCheckBox.isChecked());
					budgetRingButton.setText(getString(R.string.cancel)+getString(R.string.DoRing));
					intent.putExtra("msg", messageBundle);

					startService(intent);
				} else {
					ShowTools.toastInThread(getString(R.string.timeerror));
				}

			}

			break;

		default:
			break;
		}

	}

	/**
	 * 创建日期及时间选择对话框
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		Calendar c;
		switch (id) {
		case DATE_DIALOG:
			c = Calendar.getInstance();
			dialog = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker dp, int year,
								int month, int dayOfMonth) {

							if (month < 9 && dayOfMonth < 10) {
								DateInput.setText(year + "-0" + (month + 1)
										+ "-0" + dayOfMonth);
							} else if (month < 9 && dayOfMonth > 10) {
								DateInput.setText(year + "-0" + (month + 1)
										+ "-" + dayOfMonth);
							} else if (month > 9 && dayOfMonth < 10) {
								DateInput.setText(year + ":" + (month + 1)
										+ "-0" + dayOfMonth);
							} else {
								DateInput.setText(year + "-" + (month + 1)
										+ "-" + dayOfMonth);
							}
						}
					}, c.get(Calendar.YEAR), // 传入年份
					c.get(Calendar.MONTH), // 传入月份
					c.get(Calendar.DAY_OF_MONTH) // 传入天数
			);
			break;
		case TIME_DIALOG:
			c = Calendar.getInstance();
			dialog = new TimePickerDialog(this,
					new TimePickerDialog.OnTimeSetListener() {
						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							if (hourOfDay < 10 && minute < 10) {
								TimeInput.setText("0" + hourOfDay + ":0"
										+ minute);
							} else if (hourOfDay < 10 && minute > 10) {
								TimeInput.setText("0" + hourOfDay + ":"
										+ minute);
							} else if (hourOfDay > 10 && minute < 10) {
								TimeInput.setText(+hourOfDay + ":0" + minute);
							} else {
								TimeInput.setText(+hourOfDay + ":" + minute);
							}

						}
					}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
					false);
			break;
		}
		return dialog;
	}

	private void DeleteNotification() {

		try {
			NotificationManager notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
			notificationManager.cancel(BudgetReciver.NOTIFICATION_ID);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private boolean BudgetServiceIsStart(
			List<ActivityManager.RunningServiceInfo> mServiceList,
			String className) {

		for (int i = 0; i < mServiceList.size(); i++)

		{

			if (className.equals(mServiceList.get(i).service.getClassName()))

			{
				return true;
			}

		}

		return false;

	}

	// 获取所有启动的服务的类名
	private String getServiceClassName(
			List<ActivityManager.RunningServiceInfo> mServiceList) {
		String res = "";

		for (int i = 0; i < mServiceList.size(); i++) {

			res += mServiceList.get(i).service.getClassName() + " \n";

		}

		return res;

	}

	void saveBudget() {
		try {
		
			Editor editor = pref.edit();
			editor.putInt("weekBudget",
					Integer.parseInt(weekBudget_et.getText().toString()));
			editor.putInt("monthBudget",
					Integer.parseInt(monthBudget_et.getText().toString()));
			if (Integer.parseInt(weekBudget_et.getText().toString())<Integer.parseInt(monthBudget_et.getText().toString())) {
				editor.commit();
			}else {
				ShowTools.toastInThread(getString(R.string.budgetSave_err));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	void saveBudgetRing(String mString, String date, String time) {

		try {
			Editor editor = pref.edit();
			editor.putString("message", mString);
			editor.putBoolean("Ring", RingCheckBox.isChecked());
			editor.putString("date", date);
			editor.putString("time", time);
			// editor.putInt("monthBudget",
			// Integer.parseInt(monthBudget_et.getText().toString()));
			editor.commit();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	String readBudgetRing() {
		DateInput.setText(pref.getString("date", ""));
		TimeInput.setText(pref.getString("time", ""));
		RingCheckBox.setChecked(pref.getBoolean("Ring", true));
		return pref.getString("message", null);

	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if (buttonView == RingCheckBox) {
			if (RingCheckBox.isChecked()) {
				RingCheckBox.setText(getString(R.string.Ringremind));
				RingCheckBox.setChecked(isChecked);
			} else {
				RingCheckBox.setText(getString(R.string.Vibrationremind));
				RingCheckBox.setChecked(isChecked);
			}
		}

	}

}
